<template>
  <div class="trade_mod" :class="themeClass">
    <div class="trade_mod_box">
      <div class="trade_mod_box_tabs">
        <van-tabs v-model="activeName" @click="switchTransactions" class="moomoo-tabs" type="card" :color="'#DAAB51'">
          <!--现货交易-->
          <van-tab :title="$t('Trade.Spot goods')" name="Currency"></van-tab>
          <!--隐藏 -->
          <!--合约交易 -->
          <van-tab :title="$t('Trade.lever')" name="Fast" v-if="thisSymbolType == 1"></van-tab>
          <!--短线期权交易-->
          <van-tab :title="$t('Trade.Option')" name="Contract" v-if="thisSymbolType == 2"></van-tab>
        </van-tabs>
      </div>

      <div class="trade_mod_box_content">
        <div class="trade_mod_box_title">
          <div class="trade_mod_box_title_top">
            <div class="top-left" @click="openMarkets">
              <img v-if="isDayTime" src="@/assets/img/List@2x(1).png" alt="" />
              <img v-else src="@/assets/img/List@2x.png" alt="" />
              <h1>{{ symbol }}</h1>
            </div>
            <div class="top-right">
              <van-button v-if="activeName !== 'Currency'" :color="topBtnColor" @click="jumpPosition">{{ $t('Trade.Position') }}</van-button>
            </div>
          </div>
        </div>
        <!-- 现货 -->
        <Currency ref="Currency" v-if="activeName === 'Currency'" :themeClass="themeClass" :bgColor="bgColor" :isDayTime="isDayTime" :symbol="symbol" />
        <!-- 合约 -->
        <Fast ref="Fast" v-if="activeName === 'Fast'" :themeClass="themeClass" :bgColor="bgColor" :isDayTime="isDayTime" :symbol="symbol" />
        <!-- 短线期权 -->
        <Contract ref="Contract" v-if="activeName === 'Contract'" :themeClass="themeClass" :bgColor="bgColor" :isDayTime="isDayTime" :symbol="symbol" />
      </div>
    </div>
    <v-footer />
    <!-- 左侧弹出层 -->
    <van-popup class="market-popup" v-model="marketPopup" @close="closeMarketsData" position="left" :style="{ width: '70%' }">
      <h1>{{ $t('Trade.Currency Quotes') }}</h1>
      <van-tabs v-model="symbolType" type="card" @click="search" title-active-color="#fff" title-inactive-color="#daab51" color="#daab51">
        <van-tab v-if="activeName == 'Currency' || activeName == 'Contract'" :title="$t('Trade.precious metals')" name="2"></van-tab>
        <van-tab v-if="activeName == 'Currency' || activeName == 'Fast'" :title="$t('Trade.cryptocurrency')" name="1"></van-tab>
      </van-tabs>
      <van-tabs :before-change="tabClick" v-model="marketTabs" :color="'#FDC706'">
        <van-tab :title="$t('Trade.Optional')" name="optional"></van-tab>
        <van-tab :title="$t('Trade.market')" name="markets"></van-tab>
      </van-tabs>
      <van-search v-model="searchValue" :placeholder="$t('Trade.Search currency')" @search="search" @clear="search" :class="themeClass" input-align="center"></van-search>
      <div class="search-list">
        <div v-for="(item, index) in list" :key="index" @click="tradeDetail(item)">
          <p>
            <span class="left">{{ item.symbol }}</span>
          </p>
          <h1 :style="{ color: listBtnBgColor(item.rate) }">
            {{ item.lastPrice }}
          </h1>
        </div>
      </div>
      <van-pagination v-if="total != 0" v-model="currentPage" :total-items="total" :show-page-size="5" @change="getMarketsData">
        <template #prev-text>
          <van-icon name="arrow-left" />
        </template>
        <template #next-text>
          <van-icon name="arrow" />
        </template>
        <template #page="{ text }">{{ text }}</template>
      </van-pagination>
      <van-empty v-else image="search" :description="$t('info.info7')" />
    </van-popup>
  </div>
</template>

<script>
import Currency from '@/components/Trade/Currency/index.vue' // 现货
import Fast from '@/components/Trade/Fast/index.vue' // 合约交易
import Contract from '@/components/Trade/Contract/index.vue' // 短线期权交易
export default {
  name: 'trade',
  components: {
    Currency, // 现货
    Fast, // 合约
    Contract //短线期权
  },
  computed: {
    // 主题类名
    themeClass() {
      return this.isDayTime ? 'daytime' : 'darknight'
    },
    // 背景颜色
    bgColor() {
      return this.isDayTime ? 'black' : 'white'
    },
    // 顶部按钮颜色
    topBtnColor() {
      return this.isDayTime ? '#DAAB51' : '#000000'
    },
    socketMsgs() {
      return this.$websocket.getters.socketMsgs
    }
  },
  data() {
    return {
      activeName: 'Currency',
      isDayTime: false,
      marketPopup: false,
      marketTabs: 'markets',
      list: [],
      symbol: 'XAU/USDT',
      total: 0,
      currentPage: 1,
      symbolType: 2,
      thisSymbolType: 2,
      searchValue: ''
    }
  },
  watch: {
    '$store.state.nightMode': {
      handler(newVal) {
        this.isDayTime = newVal
      },
      immediate: true
    },
    socketMsgs: function (data) {
      if (data.type == 'markets' || data.type == 'optional') {
        this.list = data.data.data
        this.total = data.data.total
      }
    }
  },
  created() {
    let symbol = localStorage.getItem('symbol') //默认交易对
    let tradeActive = localStorage.getItem('tradeActive') //默认交易类型  Currency=现货  Fast=合约 Contract=短线期权
    let thisSymbolType = localStorage.getItem('symbolType') //默认兑币类型  1=加密货币 2=贵金属

    if (symbol != null) this.symbol = symbol
    if (tradeActive != null) this.activeName = tradeActive
    if (thisSymbolType != null) this.thisSymbolType = thisSymbolType

    if (tradeActive == 'Contract' && symbol == null && thisSymbolType == null) {
      this.symbol = 'XAU/USDT'
      this.thisSymbolType = 2
      this.activeName = tradeActive
    }

    if (tradeActive == 'Fast' && symbol == null && thisSymbolType == null) {
      this.symbol = 'BTC/USDT'
      this.thisSymbolType = 1
      this.activeName = tradeActive
    }

    if (thisSymbolType == 1 && tradeActive == 'Contract' && symbol != null) {
      this.symbol = symbol
      this.activeName = 'Fast'
      this.thisSymbolType = thisSymbolType
    }

    if (thisSymbolType == 2 && tradeActive == 'Fast' && symbol != null) {
      this.symbol = symbol
      this.activeName = 'Contract'
      this.thisSymbolType = thisSymbolType
    }

    localStorage.setItem('symbol', this.symbol)
    localStorage.setItem('symbolType', this.thisSymbolType)
    localStorage.setItem('tradeActive', this.activeName)
  },
  mounted() {},
  activated() {
    this.marketPopup = false
    this.getMarketData()
  },
  deactivated() {
    this.closeMarketData()
  },
  destroyed() {
    this.closeMarketData()
    this.closeMarketsData()
  },
  methods: {
    switchTransactions(activeName) {
      this.activeName = activeName
      localStorage.setItem('tradeActive', activeName)
    },
    // 订阅行情数据
    getMarketsData() {
      var userInfo = localStorage.getItem('userInfo')
      userInfo = userInfo != null ? JSON.parse(userInfo).token : ''
      var timer = setInterval(() => {
        if (this.$websocket.getters.getState) {
          this.$websocket.dispatch('webSocketSend', { type: this.marketTabs, symbolType: this.symbolType, token: userInfo, page: this.currentPage, search: this.searchValue })
          clearInterval(timer)
        }
      }, 1)
    },
    // 取消订阅行情数据
    closeMarketsData() {
      this.$websocket.dispatch('webSocketSend', { type: 'stop', method: 'markets' })
    },
    // 订阅货币数据
    getMarketData() {
      var timer = setInterval(() => {
        if (this.$websocket.getters.getState) {
          this.$websocket.dispatch('webSocketSend', { type: 'market', symbol: this.symbol })
          clearInterval(timer)
        }
      }, 1)
    },
    // 取消订阅货币数据
    closeMarketData() {
      this.$websocket.dispatch('webSocketSend', { type: 'stop', method: 'market' })
    },
    // 搜索货币
    search() {
      this.currentPage = 1
      this.getMarketsData()
    },
    // 涨跌颜色
    listBtnBgColor(rate) {
      let color = rate <= 0 ? '#EE3E57' : '#0BBA99'
      return color
    },
    // 打开market
    openMarkets() {
      this.marketPopup = true
      this.getMarketsData()
    },
    // 跳转持仓页面
    jumpPosition() {
      if (this.activeName === 'Fast') {
        this.$router.push('/trade/fasttransaction')
      } else if (this.activeName === 'Contract') {
        this.$router.push('/trade/contractposition')
      }
    },
    // 切换左侧顶部导航
    tabClick(index) {
      var userInfo = localStorage.getItem('userInfo')
      if (index == 'optional' && userInfo == null) {
        this.$dialog
          .confirm({
            title: this.$t('info.info20'),
            confirmButtonText: this.$t('info.info21'),
            cancelButtonText: this.$t('info.info11'),
            confirmButtonColor: 'rgb(218, 171, 81)',
            cancelButtonColor: 'rgb(218, 171, 81)',
            theme: 'round-button'
          })
          .then(() => {
            this.$router.push('/signIn')
          })
          .catch(() => {})
        return false
      }
      // 返回 Promise 来执行异步逻辑
      return new Promise(resolve => {
        this.currentPage = 1
        this.getMarketsData()
        // 在 resolve 函数中返回 true 或 false
        resolve(true)
      })
    },
    // 切换左侧币种
    tradeDetail(row) {
      if (this.activeName == 'Currency') {
        this.symbol = row.symbol
        this.$refs[this.activeName].init(this.symbol)
      }
      this.switchTransactions('Currency')

      this.symbol = row.symbol
      this.thisSymbolType = this.symbolType

      localStorage.setItem('symbol', row.symbol)
      localStorage.setItem('symbolType', this.thisSymbolType)

      this.getMarketData()

      this.marketPopup = false
    }
  }
}
</script>

<style lang="less" scoped>
@import url('./index.less');
/deep/ .van-pagination__item {
  background: #fff;
  color: #daab51;
}

// 按钮点击时的颜色
/deep/ .van-pagination__item--active {
  background: #daab51;
}

//文字未点击时的颜色
/deep/ .van-pagination__item {
  color: #daab51;
}

//文字点击时的颜色
/deep/ .van-pagination__item--active {
  color: #fff;
}
</style>
